'use client';

import { useState, useEffect, useRef } from 'react';
import { Card, Typography, Space, Spin, Empty, message } from 'antd';
import { UserOutlined } from '@ant-design/icons';
import SearchFilter from './components/SearchFilter';
import type { User, FilterOptions, UserStatus } from '@/types/user';
import UserTable from './components/UserTable';
const { Title, Text } = Typography;

// 模拟数据生成函数
const generateMockData = (count = 100): User[] => {
  const statuses: UserStatus[] = ['active', 'inactive', 'pending', 'suspended'];
  const departments = ['技术部', '市场部', '销售部', '人力资源', '财务部', '运营部'];
  const roles = ['管理员', '普通用户', '编辑', '审核员', '访客'];
  
  return Array.from({ length: count }, (_, i) => ({
    id: i + 1,
    name: `用户${i + 1}`,
    email: `user${i + 1}@example.com`,
    age: Math.floor(Math.random() * 40) + 18,
    department: departments[Math.floor(Math.random() * departments.length)],
    role: roles[Math.floor(Math.random() * roles.length)],
    status: statuses[Math.floor(Math.random() * statuses.length)],
    joinDate: new Date(Date.now() - Math.floor(Math.random() * 365) * 24 * 60 * 60 * 1000)
      .toISOString().split('T')[0],
    lastLogin: new Date(Date.now() - Math.floor(Math.random() * 30) * 24 * 60 * 60 * 1000)
      .toISOString().replace('T', ' ').slice(0, 16),
    score: Math.floor(Math.random() * 100)
  }));
};

export default function UserManagementPage() {
  // 状态管理
  const [allUsers, setAllUsers] = useState<User[]>([]);
  const [filteredUsers, setFilteredUsers] = useState<User[]>([]);
  const [loading, setLoading] = useState(true);
  const [currentPage, setCurrentPage] = useState(1);
  const [pageSize, setPageSize] = useState(10);
  const [sortField, setSortField] = useState('');
  const [sortOrder, setSortOrder] = useState<'ascend' | 'descend' | null>(null);
  const [filtersAll, setFilters] = useState<FilterOptions>({
    searchText: '',
    status: '',
    department: ''
  });
  const filtersRef = useRef<FilterOptions>(filtersAll);
useEffect(() => {
  filtersRef.current = filtersAll; // 实时同步最新状态到 ref
}, [filtersAll]);
  
  // 获取所有部门列表
  const departments = Array.from(new Set(allUsers.map(user => user.department)));

  // 初始化数据
  useEffect(() => {
    // 模拟API请求
    const timer = setTimeout(() => {
      const data = generateMockData(156);
      setAllUsers(data);
      setFilteredUsers(data);
      setLoading(false);
    }, 800);

    return () => clearTimeout(timer);
  }, []);

  // 处理筛选变化
  const handleFilterChange = (filtersParam: FilterOptions | ((prev: FilterOptions) => FilterOptions)) => {
    // 1. 解析出最终的 FilterOptions 对象（关键：处理函数式更新）
  const filters: FilterOptions = typeof filtersParam === 'function' 
    ? filtersParam(filtersRef.current) // 用当前状态执行函数，得到新条件
      : filtersParam; // 直接使用对象
    // 2. 更新状态（同步到组件状态）
  setFilters(filters);
      let result = [...allUsers];
    
      // 搜索筛选
      if (filters.searchText) {
        const lowerSearchText = filters.searchText.toLowerCase();
        result = result.filter(user =>
          user.name.toLowerCase().includes(lowerSearchText) ||
          user.email.toLowerCase().includes(lowerSearchText) ||
          user.department.toLowerCase().includes(lowerSearchText)
        );
      }
    
      // 状态筛选
      if (filters.status) {
        result = result.filter(user => user.status === filters.status);
      }
    
      // 部门筛选
      if (filters.department) {
        result = result.filter(user => user.department === filters.department);
      }
    
      // 排序处理
      if (sortField && sortOrder) {
        result.sort((a, b) => {
          const valueA = a[sortField as keyof User];
          const valueB = b[sortField as keyof User];
        
          if (valueA < valueB) return sortOrder === 'ascend' ? -1 : 1;
          if (valueA > valueB) return sortOrder === 'ascend' ? 1 : -1;
          return 0;
        });
      }
      setFilteredUsers(result);
      setCurrentPage(1); // 重置到第一页
    };

  // 处理分页变化
  const handlePageChange = (page: number, size: number) => {
    setCurrentPage(page);
    setPageSize(size);
  };

  // 处理排序变化
  const handleSortChange = (field: string, order: 'ascend' | 'descend' | null) => {
    setSortField(field);
    setSortOrder(order);
    
    // 重新筛选以应用排序
    handleFilterChange({
      searchText: '',
      status: '',
      department: ''
    });
  };

  // 处理编辑操作
  const handleEdit = (user: User) => {
    message.info(`编辑用户: ${user.name}`);
    // 实际应用中这里会打开编辑弹窗
  };

  // 处理删除操作
  const handleDelete = (id: number) => {
    setAllUsers(prev => prev.filter(user => user.id !== id));
    setFilteredUsers(prev => prev.filter(user => user.id !== id));
    message.success('删除成功');
  };

  // 获取当前页数据
  const getCurrentPageData = () => {
    const startIndex = (currentPage - 1) * pageSize;
    return filteredUsers.slice(startIndex, startIndex + pageSize);
  };

  return (
    <div className="p-6">
      <Card 
        title={
          <Space>
            <UserOutlined />
            <Title level={5} style={{ margin: 0 }}>用户管理</Title>
          </Space>
        }
        className="shadow-sm"
      >
        {/* 搜索筛选区域 */}
        <div className="mb-6">
          <SearchFilter 
            departments={departments}
            onFilterChange={handleFilterChange}
            initialValues = {filtersAll}
          />
        </div>
        
        {/* 结果统计 */}
        <div className="mb-4">
          <Text type="secondary">
            共 <Text strong>{filteredUsers.length}</Text> 条记录
          </Text>
        </div>
        
        {/* 表格区域 */}
        <Spin spinning={loading} tip="加载中...">
          {filteredUsers.length > 0 ? (
            <UserTable
              dataSource={getCurrentPageData()}
              loading={loading}
              total={filteredUsers.length}
              pageSize={pageSize}
              currentPage={currentPage}
              onPageChange={handlePageChange}
              onSortChange={handleSortChange}
              onEdit={handleEdit}
              onDelete={handleDelete}
            />
          ) : (
            <Empty 
              description="没有找到匹配的记录"
              style={{ padding: '50px 0' }}
            />
          )}
        </Spin>
      </Card>
    </div>
  );
}
    